package com.ocr.client;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;

public class PyClient {

	//public static String URL = "http://192.168.1.25:8080";
	public static String URL = "http://133.27.79.171:8080";
	public static String DEFAULT_LANGUAGE ="eng";

	public static String OCRClient(Bitmap bitmap, String language)
			throws Exception {
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost postRequest = new HttpPost(URL);

		MultipartEntity reqEntity = new MultipartEntity(
				HttpMultipartMode.BROWSER_COMPATIBLE);

		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, output);
		byte[] data = output.toByteArray();

		ByteArrayBody filedata = new ByteArrayBody(data, "the_image.jpg");
		reqEntity.addPart("uploaded", filedata);

		reqEntity.addPart("name", new StringBody("the_file"));

		String ocrlang = language(language);
		if (ocrlang != null)
			reqEntity.addPart("lang", new StringBody(ocrlang));
		else
			reqEntity.addPart("lang", new StringBody(DEFAULT_LANGUAGE));

		postRequest.setEntity(reqEntity);

		//
		HttpResponse response = httpClient.execute(postRequest);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				response.getEntity().getContent(), "UTF-8"));
		String sResponse;

		StringBuilder s = new StringBuilder();

		// Log.i(LOG_TAG, response.toString());
		while ((sResponse = reader.readLine()) != null) {
			s = s.append(sResponse).append('\n');
		}
		// Log.i(LOG_TAG, s.toString());
		// int i = s.indexOf("body");
		// int j = s.lastIndexOf("body");
		return s.toString();
	}

	public static String language(String lang) {

		Hashtable<String, String> table = new Hashtable<String, String>();
		table.put("ENGLISH", "eng");
		table.put("VIETNAMESE", "vie");
		table.put("JAPANESE", "jpn");
		
		if (table.containsKey(lang.toUpperCase()))
			return table.get(lang.toUpperCase());

		return null;

	}
}
